package com.anli02.interceptor;

import com.anli02.entity.dto.SessionwebUserDto;

import com.anli02.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      /*  HttpSession session = request.getSession();
        String token= (String) session.getAttribute("session_account");*/
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod=(HandlerMethod)handler;
        if(handlerMethod.getBean().getClass().getName().equals("springfox.documentation.swagger.web.ApiResourceController")){
            return  true;
        }

//判断如果请求的类是swagger的控制器，直接通行。



        SessionwebUserDto sessionwebUserDto = (SessionwebUserDto) request.getSession().getAttribute("session_account");
        if (sessionwebUserDto == null) {
            throw new BusinessException("用户错误");
        }
        if(sessionwebUserDto.getUserId().isEmpty()||sessionwebUserDto.getUsername().isEmpty())
        {
            throw new BusinessException("用户错误");
        }
        RequestContextHolder.currentRequestAttributes().setAttribute("user", sessionwebUserDto, RequestAttributes.SCOPE_REQUEST);
        return  true;

    }
}
